import React from "react";
import { Badge, Button, Form, Icon, Input, Modal, Popover, Radio, Tooltip } from "antd";
const FormItem = Form.Item;
import { connect } from "react-redux";
import { messages } from "share/common";
import ResizeTable from "components/resize-table";
import ListSelector from "components/list-selector";
import vendorService from "./supplier-management.service";
class AvailableUserComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      applicablePersonScope: "all",
      radioValue: "user",
      pagination: {
        total: 0,
        page: 0,
        pageSize: 10,
      },
      columns: [
        {
          title: messages("common.user.id") /*工号*/,
          dataIndex: "employeeID",
          render: (text) => {
            return (
              <Tooltip title={text} placement={"topLeft"} getPopupContainer={(triggerNode) => triggerNode.parentNode}>
                {text}
              </Tooltip>
            );
          },
        },
        {
          title: messages("basic-5.key95") /*姓名*/,
          dataIndex: "fullName",
          render: (text) => {
            return (
              <Tooltip title={text} placement={"topLeft"} getPopupContainer={(triggerNode) => triggerNode.parentNode}>
                {text}
              </Tooltip>
            );
          },
        },
        {
          title: messages("common.department") /*部门*/,
          dataIndex: "departmentName",
          render: (text) => {
            return (
              <Tooltip title={text} placement={"topLeft"} getPopupContainer={(triggerNode) => triggerNode.parentNode}>
                {text}
              </Tooltip>
            );
          },
        },
        {
          title: messages("basic-5.key163") /*职位*/,
          dataIndex: "title",
          render: (text) => {
            return (
              <Tooltip title={text} placement={"topLeft"} getPopupContainer={(triggerNode) => triggerNode.parentNode}>
                {text}
              </Tooltip>
            );
          },
        },
      ],
      columnsPersonGroup: [
        {
          title: messages("basic-5.key92") /*人员组编码*/,
          dataIndex: "code",
          render: (text) => {
            return (
              <Tooltip title={text} placement={"topLeft"} getPopupContainer={(triggerNode) => triggerNode.parentNode}>
                {text}
              </Tooltip>
            );
          },
        },
        {
          title: messages("basic-5.key93") /*人员组名称*/,
          dataIndex: "name",
          render: (text) => {
            return (
              <Tooltip title={text} placement={"topLeft"} getPopupContainer={(triggerNode) => triggerNode.parentNode}>
                {text}
              </Tooltip>
            );
          },
        },
        {
          title: messages("basic-5.key94") /*描述*/,
          dataIndex: "comment",
          render: (text) => {
            return (
              <Tooltip title={text} placement={"topLeft"} getPopupContainer={(triggerNode) => triggerNode.parentNode}>
                {text}
              </Tooltip>
            );
          },
        },
        {
          title: messages("common.column.status") /*状态*/,
          dataIndex: "enabled",
          render: (isEnabled) => (
            <Badge
              status={isEnabled ? "success" : "error"}
              text={isEnabled ? messages("basic-5.key20") /*启用temp*/ : messages("basic-5.key21") /*禁用temp*/}
            />
          ),
        },
      ],
      userData: [],
      keyword: "",
      userLoading: false,
      showPersonListSelector: false,
      selectorLoading: false,
      showDepartmentSelector: false,
      departmentSelectorLoading: false,
      showPersonGroupListSelector: false,
    };
  }

  componentWillMount() {
    if (this.props.params.vendorInfoId) {
      this.getPersonOrGroupAttr();
      this.getPersonOrGroup();
    }
  }
  componentDidMount() {
    this.setColumns(this.props.params.disabled);
  }

  componentWillReceiveProps(next) {
    if (next.params.distributeType === "userGroup") {
      this.setState({
        radioValue: "userGroup",
      });
    }
  }

  setColumns = (disabled) => {
    let columns = this.state.columns;
    let columnsPersonGroup = this.state.columnsPersonGroup;
    if (!disabled) {
      let operation = {
        title: messages("common.operation") /*操作*/,
        dataIndex: "recordId",
        render: (text) => (
          <span>
            <a onClick={(e) => this.deletePersonOrGroup(e, text)}>{messages("common.delete") /*删除*/}</a>
          </span>
        ),
      };
      let operationPersonGroup = {
        title: messages("common.operation") /*操作*/,
        dataIndex: "recordId",
        render: (text) => (
          <span>
            <a onClick={(e) => this.deletePersonOrGroup(e, text)}>{messages("common.delete") /*删除*/}</a>
          </span>
        ),
      };
      columns.push(operation);
      columnsPersonGroup.push(operationPersonGroup);
      this.setState({
        columns,
        columnsPersonGroup,
      });
    }
  };

  getPersonOrGroupAttr = () => {
    vendorService
      .getPersonOrGroupAttr(this.props.params.vendorInfoId)
      .then((res) => {
        if (res && res.data) {
          this.setState({
            applicablePersonScope: res.data.applicablePersonScope,
          });
        }
      })
      .catch((err) => {});
  };

  getPersonOrGroup = () => {
    const { keyword, pagination } = this.state;
    let params = {
      vendorInfoId: this.props.params.vendorInfoId,
      keyword,
      page: pagination.page,
      size: pagination.pageSize,
    };
    this.setState({
      userLoading: true,
    });
    vendorService
      .getPersonOrGroup(params)
      .then((res) => {
        if (res && res.data) {
          pagination.total = Number(res.headers["x-total-count"]);
          let userData = [],
            type = "";
          res.data.forEach((item) => {
            type = item.objectType;
            item[type].vendorInfoId = item.vendorInfoId;
            item[type].recordId = item.id;
            userData.push(item[type]);
          });
          // if(type){
          //   this.setState({
          //     radioValue: type,
          //   });
          // }
          this.setState({
            userData,
            pagination,
          });
        }
        this.setState({
          userLoading: false,
        });
      })
      .catch((err) => {
        this.setState({
          userLoading: false,
        });
      });
  };

  deletePersonOrGroup = (e, id) => {
    vendorService
      .deletePersonOrGroup(id)
      .then((res) => {
        this.getPersonOrGroup();
      })
      .catch((err) => {});
  };

  distributePersonOrGroup = (arr = []) => {
    const { radioValue } = this.state;
    let params = {
      objectType: radioValue, //分配类型 user 人员:,userGroup:人员组
      vendorInfoId: this.props.params.vendorInfoId, // 必填，供应商唯一标识
      users: radioValue === "user" ? arr : [], //分配类型是user，需要封装的入参，可以为空(人员和人员组切换时存在的场景)
      userGroups: radioValue === "userGroup" ? arr : [],
    };
    this.setState({
      selectorLoading: true,
    });
    vendorService
      .distributePersonOrGroup(params)
      .then((res) => {
        this.getPersonOrGroup();
        this.setState({
          selectorLoading: false,
        });
      })
      .catch((err) => {
        this.setState({
          selectorLoading: false,
        });
      });
  };
  onScopeChanged = (e) => {
    let value = e.target.value;
    this.setState({
      applicablePersonScope: value,
    });
    this.props.onScopeChange(value);
  };

  onRadioChange = (e) => {
    Modal.confirm({
      title: messages("basic-5.key80") /*确认切换*/,
      content: messages("basic-5.key81") /*切换后已选数据将被清空，确认切换?*/,
      okText: messages("basic-5.key45") /*确认*/,
      cancelText: messages("common.cancel") /*取消*/,
      onOk: () => {
        this.setState(
          {
            radioValue: e.target.value,
            pagination: { total: 0, page: 0, pageSize: 10 },
          },
          () => {
            this.distributePersonOrGroup();
          }
        );
      },
    });
  };
  onChangePager = (pagination) => {
    this.setState(
      {
        pagination: {
          page: pagination.current - 1,
          pageSize: pagination.pageSize,
        },
      },
      () => {
        this.getPersonOrGroup();
      }
    );
  };

  handlePersonSelectorOpen = () => {
    const { radioValue } = this.state;
    let showPersonGroup = radioValue === "userGroup";
    if (showPersonGroup) {
      this.setState({
        showPersonGroupListSelector: true,
      });
    } else {
      this.setState({
        showPersonListSelector: true,
      });
    }
  };

  handlePersonSelectorOk = (data) => {
    if (!data.result.length) {
      return;
    }
    let result = data.result.map((item) => {
      return { id: item.id };
    });
    this.distributePersonOrGroup(result);
    this.setState({
      showPersonListSelector: false,
    });
  };

  handlePersonGroupSelectorOk = (data) => {
    if (!data.result.length) {
      return;
    }
    let result = data.result.map((item) => {
      return { id: item.id };
    });
    this.distributePersonOrGroup(result);
    this.setState({
      showPersonGroupListSelector: false,
    });
  };

  handlePersonSelectorCancel = (isPersonGroup) => {
    if (isPersonGroup) {
      this.setState({
        showPersonGroupListSelector: false,
      });
    } else {
      this.setState({
        showPersonListSelector: false,
      });
    }
  };

  goToThePage = (e) => {
    e.preventDefault();
    window.open(`/main/setting/person-group/`);
  };

  //搜索自定义值列表项的部门
  clearKeyword = () => {
    this.setState({ keyword: "" }, () => {
      this.getPersonOrGroup();
    });
  };

  onChangeKeyword = (e) => {
    this.setState({ keyword: e.target.value });
  };

  onPressEnter = () => {
    const { pagination } = this.state;
    pagination.page = 0;
    this.setState(
      {
        pagination,
      },
      () => {
        this.getPersonOrGroup();
      }
    );
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const {
      radioValue,
      applicablePersonScope,
      columns,
      columnsPersonGroup,
      userData,
      pagination,
      userLoading,
      showPersonListSelector,
      selectorLoading,
      showPersonGroupListSelector,
      keyword,
    } = this.state;
    const { vendorInfoId, disabled, companyOID, formItemLayout, distributeType } = this.props.params;
    const suffix = keyword ? <Icon type="close-circle" onClick={this.clearKeyword} /> : <span />;
    return (
      <div>
        <FormItem
          label={
            <span>
              {messages("basic-5.key15") /*适用人员*/}
              <Popover content={messages("basic-7.key95") /*供应商可被使用的人员范围为所属组织范围和适用人员间取交集*/}>
                &nbsp;
                <Icon type="info-circle-o" style={{ cursor: "pointer", color: "rgba(0,0,0,0.5)" }} />
              </Popover>
            </span>
          }
          {...formItemLayout}
        >
          <Radio.Group onChange={this.onScopeChanged} value={applicablePersonScope} disabled={disabled}>
            <Radio value={"all"}>{messages("basic-5.key522") /*全员*/}</Radio>
            <Radio value={"part"}>{messages("basic-5.key9") /*部分*/}</Radio>
          </Radio.Group>
        </FormItem>
        {applicablePersonScope === "part" && vendorInfoId && (
          <div>
            <div className="standard-divider-title" style={{ margin: 0 }}>
              {messages("basic-5.key519") /*适用范围*/}
            </div>
            <FormItem label=" " {...formItemLayout}>
              <Radio.Group onChange={this.onRadioChange} value={radioValue} disabled={disabled}>
                <Radio value={"user"}>{messages("basic-5.key512") /*按人员*/}</Radio>
                <Radio value={"userGroup"}>{messages("basic-5.key513") /*按人员组*/}</Radio>
              </Radio.Group>
              <div>
                <div>
                  <Button
                    type="primary"
                    className="top-gap"
                    onClick={this.handlePersonSelectorOpen}
                    disabled={disabled}
                    loading={selectorLoading}
                  >
                    {
                      radioValue === "user"
                        ? messages("basic-5.key514") /*批量添加员工*/
                        : messages("basic-5.key96") /*添加人员组*/
                    }
                  </Button>
                  {radioValue === "userGroup" && (
                    <span style={{ marginLeft: "20px" }}>
                      {messages("basic-5.key97") /*需要设置人员组*/}，
                      <a
                        onClick={(e) => {
                          this.goToThePage(e);
                        }}
                      >
                        {messages("basic-5.key98") /*点击跳转*/}
                      </a>
                    </span>
                  )}
                  <div className="table-header-buttons inline-gap">
                    <div className="f-left total-title">
                      {
                        messages("common.total", {
                          arg1: pagination.total,
                        }) /*共搜索到 {arg1} 条数据*/
                      }
                    </div>
                    <div className="table-header-inp f-right">
                      <Input
                        style={{ width: 300 }}
                        className="item-user-name-search"
                        key={"customValueItemUserName-search"}
                        placeholder={
                          (radioValue === "user"
                            ? messages("basic-5.key515") /*输入姓名/工号*/
                            : messages("basic-5.key516")) /*输入人员组名称/编码*/ +
                          "，" +
                          messages("basic-7.key96") /*回车进行搜索*/
                        }
                        prefix={<Icon type="search" className="font-disabled" />}
                        suffix={suffix}
                        value={keyword}
                        onChange={this.onChangeKeyword}
                        onPressEnter={this.onPressEnter}
                      />
                    </div>
                    <div className="clear" />
                  </div>
                </div>
                <ResizeTable
                  columns={radioValue === "user" ? columns : columnsPersonGroup}
                  dataSource={userData}
                  pagination={pagination}
                  loading={userLoading}
                  onChange={this.onChangePager}
                  rowKey="id"
                  bordered
                  size="middle"
                />
              </div>
            </FormItem>
          </div>
        )}
        <ListSelector
          type="user"
          visible={showPersonListSelector}
          onOk={this.handlePersonSelectorOk}
          onCancel={this.handlePersonSelectorCancel}
          labelKey={"fullName"}
          extraParams={{ companyOID }}
          confirmLoading={selectorLoading}
        />
        <ListSelector
          type="user_group"
          visible={showPersonGroupListSelector}
          onOk={this.handlePersonGroupSelectorOk}
          onCancel={() => {
            this.handlePersonSelectorCancel(true);
          }}
          labelKey={"name"}
          confirmLoading={selectorLoading}
        />
      </div>
    );
  }
}
AvailableUserComponent.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    user: state.login.user,
    currentMenuPermission: state.main.currentMenuPermission,
    authPolicyAll: state.main.authPolicyAll,
  };
}

const wrappedNewSupplierInfo2 = Form.create()(AvailableUserComponent);
export default connect(mapStateToProps)(wrappedNewSupplierInfo2);
